<template>
  <el-scrollbar>
    <div class="bottom-right-component" v-loading="loading">
      <!-- 收藏的社团 -->
      <div v-if="content === 'collection'" >
        <h3 >我收藏的社团如下：</h3>
        <el-row  :gutter="20">
          <el-col :span="24" v-for="collection in collections" :key="collection.clubId">
            <el-card class="club-card">
              <el-link
                type="primary"
                class="club-link"
                @click="navigateToClub(collection.clubId)"
              >
                <el-icon class="icon"><StarFilled /></el-icon><!-- 收藏图标 -->
                <div class="club-info" >
                  <h4>{{ collection.clubName }}</h4>
                  <p>类别: {{ collection.category }}</p>
                </div>
                <img :src="collection.logoUrl " alt="profile" class="profile-image" />
              </el-link>
            </el-card>
          </el-col>
        </el-row>
        <el-pagination
            background
            layout="prev, pager, next,total"
            :total="totalCollection"
            :page-size="collectionPageSize"
            @current-change="collectionPageChange"
        ></el-pagination>
      </div>

      <!-- 申请的社团 -->
      <div v-else-if="content === 'application'" >
        <h3>我申请的社团如下：</h3>
        <el-row  :gutter="20">
          <el-col :span="24" v-for="application in applications" :key="application.clubId">
            <el-card class="club-card">
              <el-link
                type="primary"
                class="club-link"
                @click="navigateToClub(application.clubId)"
              >
                <el-icon class="icon"><DocumentAdd /></el-icon> <!-- 申请图标 -->
                <div class="club-info">
                  <h4>{{ application.clubName }}</h4>
                  <p>类别: {{ application.category }} - 申请状态: {{ application.approvalStatus }}</p>
                </div>
                <img :src="application.logoUrl" alt="profile" class="profile-image" />
              </el-link>
            </el-card>
          </el-col>
        </el-row>
        <el-pagination
            background
            layout="prev, pager, next,total"
            :total="totalApplication"
            :page-size="applicationPageSize"
            @current-change="applicationPageChange"
        ></el-pagination>
      </div>

      <!-- 参与的社团 -->
      <div v-else-if="content === 'participation'" >
        <h3>我参与的社团如下：</h3>
        <el-row  :gutter="20">
          <el-col :span="24" v-for="participation in participations" :key="participation.clubId">
            <el-card class="club-card">
              <el-link
                type="primary"
                class="club-link"
                @click="navigateToClub(participation.clubId)"
              >
                <el-icon class="icon"><User /></el-icon> <!-- 参与图标 -->
                <div class="club-info">
                  <h4>{{ participation.clubName }}</h4>
                  <p>类别: {{ participation.category }} - 职位: {{ participation.clubPosition }}</p>
                </div>
                <img :src="participation.logoUrl " alt="profile" class="profile-image" />
              </el-link>
            </el-card>
          </el-col>
        </el-row>
        <el-pagination
            background
            layout="prev, pager, next,total"
            :total="totalParticipation"
            :page-size="participationPageSize"
            @current-change="participationPageChange"
        ></el-pagination>
      </div>

      <!-- 管理的社团 -->
      <div v-else-if="content === 'management'" >
        <h3>我管理的社团如下：</h3>
        <el-row  :gutter="20">
          <el-col :span="24" v-for="management in managements" :key="management.clubId">
            <el-card class="club-card">
              <el-link
                type="primary"
                class="club-link"
                @click="navigateToManagement(management)"
              >
                <el-icon class="icon"><Setting /></el-icon> <!-- 管理图标 -->
                <div class="club-info">
                  <h4>{{ management.clubName }}</h4>
                  <p>类别: {{ management.category }} - 职位: {{ management.clubPosition }}</p>
                </div>
                <img :src="management.logoUrl ? management.logoUrl:'https://crazyhat.oss-cn-beijing.aliyuncs.com/img/9e145d09-1378-4c93-a384-53fb51f29a89.png'" alt="profile" class="profile-image" />
                <div class="status-indicator" :style="[getStatusStyle(management.clubStatus), { marginLeft: '10px' }]">
                  {{ management.clubStatus || '审核中' }}
                </div>
              </el-link>
            </el-card>
          </el-col>
        </el-row>
        <el-pagination
            background
            layout="prev, pager, next,total"
            :total="totalManage"
            :page-size="managePageSize"
            @current-change="managePageChange"
        ></el-pagination>
      </div>
    </div>
  </el-scrollbar>
</template>

<script>
import axios from 'axios';
import { Card, Col, Row, Icon as ElIcon, ElMessage } from 'element-plus';
import { StarFilled, DocumentAdd, User, Setting } from '@element-plus/icons-vue';
import { ElLoading } from 'element-plus';

export default {
  name: "BottomRightComponent",
  components: {
    // ElCard: Card,
    // ElCol: Col,
    // ElRow: Row,
    // ElLink: Link,

    StarFilled, DocumentAdd, User, Setting
  },
  props: {
    content: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      loading: false,
      collections: [],
      applications: [],
      participations: [],
      managements: [],
      isLoading: false,

      totalCollection:0,
      currentCollectionPage: 1,
      collectionPageSize:5,

      totalApplication:0,
      currentApplicationPage: 1,
      applicationPageSize:5,

      totalParticipation:0,
      currentParticipationPage: 1,
      participationPageSize:5,

      totalManage:0,
      currentManagePage: 1,
      managePageSize:5,

      statusConfig: {
        '审核中': { class: 'status-pending', color: '#ffd700', textColor: '#8b4513' },
        '开放中': { class: 'status-open', color: '#90ee90', textColor: '#006400' },
        '限制加入': { class: 'status-restricted', color: '#f08080', textColor: '#8b0000' },
      }
    };
  },
  computed: {
    getStatusStyle() {
      return (status) => {
        // 如果状态是 undefined 或 null，使用 '审核中' 作为默认值
        const safeStatus = status || '审核中';
        const config = this.statusConfig[safeStatus] || { color: '#ffd700', textColor: '#8b4513' };
        return {
          backgroundColor: config.color,
          color: config.textColor
        };
      };
    }
  },
  created() {
      if (this.content === 'collection') {
        this.fetchCollections();
      } else if (this.content === 'participation') {
        this.fetchParticipations();
      } else if (this.content === 'management') {
        this.fetchManagements();
      } else if (this.content === 'application') {
        this.fetchApplications();
      }
  },
  watch: {
    async content(newContent) {
        if (newContent === 'collection') {
          await this.fetchCollections();
        } else if (newContent === 'participation') {
          await this.fetchParticipations();
        } else if (newContent === 'management') {
          await this.fetchManagements();
        } else if (newContent === 'application') {
          await this.fetchApplications();
        }
    }
  },

  methods: {
    async fetchClubInfo(clubId) {
      try {
        const response = await axios.post("/club/clubInfo", null, {
          params: { clubId:clubId }
        });
        if (response.data.code === 0) {
          return response.data.data;
        } else {
          console.error("Failed to fetch club info:", response.data.message);
          return null;
        }
      } catch (error) {
        console.error("Error fetching club info:", error);
        return null;
      }
    },
    async fetchCollections() {
      try {
        this.loading=true;
        const response = await axios.get("/favorite/personalFavorite", {
          params: { pageNum: this.currentCollectionPage, pageSize: this.collectionPageSize }
        });
        if (response.data.code === 0) {
          this.totalCollection=response.data.data.total
          const favoriteRecords = response.data.data.records;
          this.collections = await Promise.all(favoriteRecords.map(async (favorite) => {
            const clubInfo = await this.fetchClubInfo(favorite.clubId);
            return clubInfo ? {
              clubId:clubInfo.clubId,
              clubName:clubInfo.clubName,
              category:clubInfo.category,
              favoritedTime: favorite.favoritedTime,
              logoUrl:clubInfo.logoUrl
            } : favorite;
          }));
          this.loading=false;
        } else {
          console.error("Failed to fetch collections:", response.data.message);
        }
      } catch (error) {
        console.error("Error fetching collections:", error);
      }
    },
    async fetchParticipations() {
      try {
        this.loading=true;
        const response = await axios.get("/participation/personalParticipation", {
          params: { pageNum: this.currentParticipationPage, pageSize: this.participationPageSize }
        });

        if (response.data.code === 0) {
          this.totalParticipation=response.data.data.total
          const participationRecords = response.data.data.records;
          this.participations = await Promise.all(participationRecords.map(async (participation) => {
            const clubInfo = await this.fetchClubInfo(participation.clubId);
            return clubInfo ? {
              clubId:clubInfo.clubId,
              clubName:clubInfo.clubName,
              category:clubInfo.category,
              clubPosition: participation.clubPosition,
              participateTime: participation.participateTime,
              logoUrl:clubInfo.logoUrl
            } : participation;
          }));
          this.loading=false;
        } else {
          console.error("Failed to fetch participation:", response.data.message);
        }
      } catch (error) {
        console.error("Error fetching participation:", error);
      }
    },
    async fetchApplications() {
      try {
        this.loading=true;
        const response = await axios.get("/user/personalApplications", {
          params: { pageNum: this.currentApplicationPage, pageSize: this.applicationPageSize }
        });

        if (response.data.code === 0) {
          this.totalApplication=response.data.data.total
          const applicationRecords = response.data.data.records;
          this.applications = await Promise.all(applicationRecords.map(async (application) => {
            const clubInfo = await this.fetchClubInfo(application.clubId);
            return clubInfo ? {
              clubId:clubInfo.clubId,
              clubName:clubInfo.clubName,
              category:clubInfo.category,
              approvalStatus: application.approvalStatus,
              applyTime: application.applyTime,
              logoUrl:clubInfo.logoUrl
            } : application;
          }));
          this.loading=false;
        } else {
          console.error("Failed to fetch applications:", response.data.message);
        }
      } catch (error) {
        console.error("Error fetching applications:", error);
      }
    },
    async fetchManagements() {
      try {
        this.loading=true;
        const response = await axios.get("/manage/personalManage", {
          params: { pageNum: this.currentManagePage, pageSize: this.managePageSize}
        });

        if (response.data.code === 0) {
          this.totalManage=response.data.data.total
          const managementRecords = response.data.data.records;
          this.managements = await Promise.all(managementRecords.map(async (management) => {
            const clubInfo = await this.fetchClubInfo(management.clubId);
            return clubInfo ? {
              clubId:clubInfo.clubId,
              clubName:clubInfo.clubName,
              category:clubInfo.category,
              logoUrl:management.logoUrl,
              clubPosition: management.clubPosition,
              clubStatus:clubInfo.clubStatus
            } : management;
          }));
          this.loading=false;
        } else {
          console.error("Failed to fetch managements:", response.data.message);
        }
        this.loading=false;
      } catch (error) {
        console.error("Error fetching managements:", error);
        this.loading=false;
      }
    },
    navigateToClub(clubId) {
      this.$router.push({ name: "ClubDetail", query: { clubId: clubId } });
    },
    navigateToManagement(management) {
      if (management.clubPosition === '一把手') {
        this.$emit('switch-to-leader', management);
      } else if (management.clubPosition === '二把手') {
        this.$emit('switch-to-second-leader', management);
      }
    },
    collectionPageChange(page) {
      this.currentCollectionPage = page;
      this.fetchCollections(page);
    },
    applicationPageChange(page) {
      this.currentApplicationPage = page;
      this.fetchApplications(page);
    },
    participationPageChange(page) {
      this.currentParticipationPage = page;
      this.fetchParticipations(page);
    },
    managePageChange(page) {
      this.currentManagePage = page;
      this.fetchManagements(page);
    }
  }
};
</script>

<style scoped>
.bottom-right-component {
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  max-height: 90%;
  background-color: #f9f9f9; /* 背景色 */
  border-radius: 8px; /* 圆角边框 */
}

h3 {
  margin-bottom: 1em;
  color: #333;
  font-size: 1.75em; /* 标题字体大小 */
  text-align: center; /* 标题居中 */
}

.el-row {
  margin-bottom: 20px;
  justify-content: center; /* 内容居中 */
}

.el-col {
  margin-bottom: 10px;
}

.club-card {
  width: 100%; /* 卡片宽度占满 */
  background-color: #fff; /* 白色背景 */
  border-radius: 12px; /* 圆角 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); /* 阴影 */
  overflow: hidden;
  transition: box-shadow 0.3s, transform 0.3s;
  margin: 0px; /* 左右外边距 */
  display: flex; /* 使用 Flexbox 布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  flex-direction: column; /* 子元素排列为列 */
  padding: 20px; /* 内边距 */
  box-sizing: border-box; /* 边框计算在宽度内 */
}

.club-card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.25);
  transform: translateY(-3px);
}

.club-link {
  display: flex;
  align-items: center;
  color: inherit; /* 文字颜色继承 */
  text-decoration: none; /* 去除下划线 */
  padding: 15px; /* 内边距 */
  width: 100%; /* 链接宽度占满 */
  text-align: center;
}

.icon {
  margin-right: 10px; /* 图标与文本间距 */
  font-size: 24px; /* 图标大小 */
}

.club-info {
  flex-grow: 1; /* 社团信息占据剩余空间 */
  display: flex;
  flex-direction: column; /* 确保文本块为列布局 */
  align-items: center; /* 水平居中 */
  text-align: center; /* 文本居中 */
  width: 100%; /* 确保文本容器占满卡片宽度 */
  text-align: center;
}

.club-link h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 1.25em;
  font-weight: 500;
  display: flex; /* 使用 Flexbox 布局 */
  flex-direction: column; /* 子元素排列为列 */
  justify-content: center; /* 垂直居中 */
  align-items: center;
  width: 100%; /* 链接宽度占满 */
  padding: 10px; /* 根据需要调整内边距 */
  text-decoration: none;
  color: inherit;
  text-align: center;
}

.club-link p {
  margin: 0;
  color: #666;
  font-size: 1em;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin: 20px;
}

.profile-image {
  border-radius: 50%;
  width: 70px;
  height: 70px;
  margin-bottom: 10px;
}

.status-indicator {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 15px;
  font-weight: bold;
  text-align: center;
}
.status-indicator {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 15px;
  font-weight: bold;
  text-align: center;
}
/* 适配小屏幕设备 */
@media (max-width: 768px) {


  .club-link {
    flex-direction: column; /* 垂直排列 */
    text-align: center; /* 文本居中 */
  }

  .icon {
    display: block; /* 图标独占一行 */
    margin: 0 auto 10px; /* 自动左右外边距 */
  }

  .club-info {
    padding: 10px; /* 内边距调整 */
  }

  .club-link h4, .club-link p {
    margin: 5px 0; /* 调整标题和文本的外边距 */
  }
}
</style>
